package com.whw.service.impl;

import com.whw.dao.MyUserDao;
import com.whw.model.MyUser;
import com.whw.service.MyUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by YangZhi on 2016/1/15.
 */
@Service
@Transactional
public class MyUserServiceImpl implements MyUserService {

    @Resource
    private MyUserDao myUserDao;

    @Override
    public MyUser login(String account, String password) {
        return myUserDao.findByAccountAndPassword(account,password);
    }

    @Override
    public MyUser updateMyUser(MyUser updateMyUser) {
        myUserDao.saveOrUpdate(updateMyUser);
        return updateMyUser;
    }

    @Override
    public boolean updatePass(int id,String oldPassword, String newPassword) {
        MyUser myUser=myUserDao.findById(id);
        if(login(myUser.getAccount(),oldPassword)==null){
            return false;
        }
        myUser.setPassword(newPassword);
        myUserDao.saveOrUpdate(myUser);
        return true;
    }

    @Override
    public MyUser findById(int id) {
        return myUserDao.findById(id);
    }

    @Override
    public boolean deleteById(int id) {
        MyUser myUser = findById(id);
        if(myUser==null) return false;
        myUserDao.delete(myUser);
        return true;
    }

    @Override
    public boolean addMyUser(MyUser myUser) {
        MyUser my = myUserDao.findByEmail(myUser.getEmail());
        if (my!=null)return false;
        myUserDao.save(myUser);
        return true;
    }

    @Override
    public MyUser findByName(String name) {
        List<MyUser> list = myUserDao.findByName(name);
        if(list==null||list.size()==0)return null;
        else return list.get(0);
    }
}
